package com.tfy.liquor.controller.fileUpload;

import com.tfy.liquor.bean.Result;
import com.tfy.liquor.service.fileUpload.ImageFileService;
import com.tfy.liquor.util.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping(value = "/image")
public class ImageFileController {
    private final static Logger logger = LoggerFactory.getLogger(ImageFileController.class);

    @Autowired
    private ImageFileService imageFileService;

    /**
     * 文件上传测试接口 * @return
     */
    @RequestMapping("/upload")
    public Result uploadFileTest(@RequestParam("imageFile") MultipartFile imageFile) {
        return imageFileService.uploadImageFile(imageFile);
    }

    /**
     * 获取图片
     *
     * @param response
     * @param imageFile
     */
    @RequestMapping("/load")
    public void load(HttpServletResponse response, String imageFile) {
        // 获取文件后缀名称
        assert imageFile != null;
        String fileSuffix = imageFile.substring(imageFile.lastIndexOf("."));
        String param;
        // jpg格式的文件如果使用png去解析，占用空间会增加5倍，实际测试达到16倍，所以需要进行优化，防止带宽占用过多
        if (fileSuffix.toUpperCase().contains("JPG") || fileSuffix.toUpperCase().contains("JPEG")) {
            param = "jpg";
        } else {
            param = "png";
        }
        try {
            String path = "/www/wwwroot/springboot/";
            // 文件保存的路径
            path += "images" + File.separator;
            BufferedImage image = ImageIO.read(new File(path + imageFile));
            response.setHeader("Cache-Control", "no-store, nocache");
            response.setContentType("image/" + param);
            ServletOutputStream outputStream = response.getOutputStream();
            ImageIO.write(image, param, outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //获取运行根目录
    @RequestMapping("/test")
    public Result uploadFileTest() {
        File path = null;
        try {
            path = new File(ResourceUtils.getURL("classpath:").getPath());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if (!path.exists()) path = new File("");
        System.err.println("path:" + path.getAbsolutePath());
        return new Result().ok("path:" + path.getAbsolutePath());
    }

    /**
     * 文件上传2
     */
    @RequestMapping("/upload2")
    public Result upload2(@RequestParam("imageFile") MultipartFile imageFile) {
        String path = "/www/wwwroot/images";
        String url = null;
        try {
//            path = new File(ResourceUtils.getURL("classpath:").getPath());
            url = FileUtil.upLoadFile(imageFile, path);
        } catch (IOException ioException) {
            ioException.printStackTrace();
            return new Result().error("上传失败！");
        }
        Map<String, String> map = new HashMap<>();
        map.put("url", "http://192.168.124.22:8088/" + url);
        return new Result(map).ok("上传成功！");
    }

}
